package com.zline.foodraise.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.photoselector.domain.PhotoSelectorDomain;
import com.photoselector.listener.OnLocalReccentListener;
import com.photoselector.listener.OnPhotoItemCheckedListener;
import com.photoselector.listener.PhotoItemListener;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoPreviewActivity;
import com.photoselector.util.CommonUtils;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.NewPhotoSelectorAdapter;
import com.zline.foodraise.adapter.RemovedPhotoAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.TemplateBean;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by heshantao on 15/8/22.
 * 带模板的图片选择
 */
//resName 主要用于当一个工程为lib库的时候
@EActivity(resName = "activity_photo_selector_template")
@WindowFeature(Window.FEATURE_NO_TITLE)
public class PhotoSelectWithTemplateActivity extends Activity
        implements OnLocalReccentListener, RecyclerItemClicked
        , PhotoItemListener, OnPhotoItemCheckedListener {
    private static final String LOG_TAG = PhotoSelectWithTemplateActivity.class.getSimpleName();
    //标题
    @StringRes(resName = "select_photos")
    String title;
    @ViewById(resName = "app_common_header_title_tv")
    TextView title_tv;
    @ViewById(resName = "choose_pics_num_hint_tv")
    TextView pic_num_hint_tv;
    @ViewById(resName = "pics_num_tv")
    TextView pic_num_tv;
    @ViewById(resName = "local_pics_rv")
    RecyclerView photo_select_rv;
    @ViewById(resName = "selected_pics_rv")
    RecyclerView selected_rv;
    @ViewById(resName = "choose_pics_next_step_tv")
    TextView next_step_tv;
    //最多可以选择几张图片
    @Extra
    int maxPicNmu;
    @Extra
    long templateId;
    @Extra
    long projectId;
    @Extra
    ArrayList<TemplateBean> templateArry;
    //选中是第几个模板
    @Extra
    int mPosition;
    @Bean
    NewPhotoSelectorAdapter selectorAdapter;
    @Bean
    RemovedPhotoAdapter removabledapter;
    SparseArray<PhotoModel> photosArray, selectedArray;
    List<PhotoModel> selectedList;
    PhotoSelectorDomain photoSelectorDomain;


    @AfterViews
    void doSomeAfterViews() {
        initData();
        initView();
        setPicAlbumRecyclerView();
        setRemovableRecyclerView();
        getRecentPhotos();
    }


    void initData() {
        photosArray = new SparseArray<PhotoModel>();
        selectedArray = new SparseArray<PhotoModel>();
        selectedList = new ArrayList<PhotoModel>();
    }

    void initView() {
        title_tv.setText(title);
        pic_num_hint_tv.setText(String.format(getString(R.string.select_pics_num_hint), maxPicNmu));

    }

    //获得最近使用的相册图片列表
    void getRecentPhotos() {
        photoSelectorDomain = new PhotoSelectorDomain(getApplicationContext());
        photoSelectorDomain.getReccent(this);
    }


    //设置图片相册recyclerView
    void setPicAlbumRecyclerView() {
        //photo_select_rv.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        photo_select_rv.setLayoutManager(layoutManager);
        selectorAdapter.setAdapterData(photosArray);
        selectorAdapter.setRecycleItemClickListener(this);
        selectorAdapter.setPhotoItemCheckListener(this);
        selectorAdapter.setPhotoItemListener(this);
        photo_select_rv.setAdapter(selectorAdapter);
        photo_select_rv.setItemAnimator(new DefaultItemAnimator());//设置动画
    }


    //已选择的图片带删除的RecyclerView
    void setRemovableRecyclerView() {
        selected_rv.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        selected_rv.setLayoutManager(layoutManager);
        removabledapter.setAdapterData(selectedArray);
        removabledapter.setRecycleItemClickListener(this);
        selected_rv.setAdapter(removabledapter);
        selected_rv.setItemAnimator(new DefaultItemAnimator());//设置动画
    }

    //获得图片列表
    @Override
    public void onPhotoLoaded(List<PhotoModel> photos) {
        SparseArray<PhotoModel> sparseArray = new SparseArray<PhotoModel>();
        for (int i = 0; i < photos.size(); i++) {
            PhotoModel photoModel = photos.get(i);
            if (selectedList.contains(photoModel)) {
                photoModel.setChecked(true);
            }
            sparseArray.put(i, photoModel);
        }
        selectorAdapter.addAll(sparseArray);
    }

    //图片选择是否达到最大值
    @Override
    public boolean reachMax() {
        return selectedList.size() >= maxPicNmu;
    }

    //点击图片查看详情
    void preViewPhoto(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putString("album", getResources().getString(R.string.recent_photos));
        CommonUtils.launchActivity(this, PhotoPreviewActivity.class, bundle);
    }

    @Override
    public void onRecyclerItemClicked(int position) {
        //preViewPhoto(position);
        PhotoModel photoModel = selectorAdapter.getArrys().get(position);
        if (photoModel != null) {
            String filePath = photoModel.getOriginalPath();
            TemplateProcessActivity_.intent(this).localPic(filePath).
            position(mPosition).templateArry(templateArry).start();
        }
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {
        unCheckAlubmPic(position);
    }

    void changePicNumAndNextStepStatus() {
        setSelectPicNum();
        if (selectedList.size() < maxPicNmu) {
            next_step_tv.setBackgroundResource(R.drawable.next_step_tv_unable_bg);
        } else {
            next_step_tv.setBackgroundResource(R.drawable.next_step_tv_able_bg);
        }
    }

    //设置被选中的图片的数量
    void setSelectPicNum() {
        pic_num_tv.setText(selectedList.size() + "");
    }

    //checkbox 监听
    @Override
    public void onCheckedChanged(PhotoModel photoModel, CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            if (!selectedList.contains(photoModel)) {
                if (selectedList.size() >= maxPicNmu) {
                    TUtil.showShort(this, String.format(getString(R.string.max_img_limit_reached), maxPicNmu));
                    buttonView.setChecked(false);//当选择图片超过最大值，取消选中状态

                } else {
                    removabledapter.addItem(removabledapter.arrys.size(), photoModel);
                    selectedList.add(photoModel);

                }

            }
        } else {
            if (selectedList.contains(photoModel)) {
                removedSelectPic(photoModel);
                selectedList.remove(photoModel);
            }
        }

        changePicNumAndNextStepStatus();
    }

    //底部recyclerView取消选择当前pic
    void removedSelectPic(PhotoModel photoModel) {
        if (selectedList.contains(photoModel)) {
            int position = selectedList.indexOf(photoModel);
            removabledapter.removeFromMiddleItem(position);
        }
    }

    //取消相册中的选中状态
    void unCheckAlubmPic(int position) {
        PhotoModel photoModel = selectedList.get(position);
        int albumPosition = selectorAdapter.arrys.indexOfValue(photoModel);
        selectorAdapter.arrys.get(albumPosition).setChecked(false);
        selectorAdapter.notifyItemChanged(albumPosition);
        selectedList.remove(position);
        removabledapter.removeFromMiddleItem(position);
        changePicNumAndNextStepStatus();
        Log.i(LOG_TAG, "_______第几个________" + albumPosition);
    }

    //返回
    @Click(resName = "app_common_header_left_icon_iv")
    void goBackClick() {
        goback();
    }

    //下一步
    @Click(resName = "choose_pics_next_step_tv")
    void goNextStep() {
        if (selectedList.size() < maxPicNmu) {
            TUtil.showShort(this, String.format(getString(R.string.select_pics_num_hint), maxPicNmu));
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        goback();
    }

    /**
     * 返回键 时候的动画
     */
    public void goback() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.TEMPLATE_PIC_CHOOSE);

    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.TEMPLATE_PIC_CHOOSE);
    }
}
